class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


# 递归
# class Solution(object):
#     def postorderTraversal(self, root):
#         """
#         :type root: TreeNode
#         :rtype: List[int]
#         """
#         return_list = []
#
#         def search(root):
#             if root:
#                 search(root.left)
#                 search(root.right)
#                 return_list.append(root.val)
#
#         search(root)
#         return return_list


# 迭代
class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        return_list = []
        if not root:
            return return_list
        stack = [root]
        prev = root
        while stack:
            if stack[-1].left:
                stack.append(stack[-1].left)
            else:
                while stack:
                    node = stack.pop()
                    if not node.right:
                        return_list.append(node.val)
                    else:
                        if node.right == prev:
                            return_list.append(node.val)
                        else:
                            stack.append(node)
                            stack.append(node.right)
                            break
                    prev = node
        return return_list

